package stack;


import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-07-14
 * Time: 23:21
 */
public class MyStack {
    public int[] elem;
    public int usedSize;

    public MyStack() {
        this.elem = new int[10];

    }

    //压栈
    public void push(int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }

        this.elem[usedSize++] = val;
    }

    public boolean isFull() {
      return this.usedSize == elem.length;
    }


    //判空
    public boolean isEmpty() {
        return this.usedSize == 0;
    }

    //出栈->获取栈顶元素，并且元素可以被覆盖
    public int pop() {
        if (isEmpty()) {
            throw new ExceptionEmpty("栈是空的！！！");
        }

       int val = this.elem[this.usedSize-1];
        this.usedSize--;//要减减，为后续push可以覆盖元素
        return val;
    }

    //在不删除元素前提下获取栈顶元素
    public int peek() {
        if (isEmpty()) {
            throw new ExceptionEmpty("栈是空的！！！");
        }

        int val = this.elem[this.usedSize-1];
        //不用要减减

        return val;
    }

    //栈的压入、弹出序列
    public boolean IsPopOrder (int[] pushV, int[] popV) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int j = 0;
        for(int i = 0; i < pushV.length; i++) {
            stack.push(pushV[i]);

            /**
             * 这里注意stack.peek() == popV[j]，不能写入while循环，不然栈顶元素和popV元素，
             *              不相等，会一直死循环i不会加加，就没法压入pushV的下一个元素
             */
            //注意压栈的同时，和popV[j]比较，不相同借助for循环继续往后压栈
            while(!stack.empty() && j < pushV.length &&
                    stack.peek() == popV[j]) {
                    stack.pop();
                    j++;
            }
        }

        return stack.empty();
    }
}
